package com.mj.mafeed.dao;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.mj.mafeed.bean.MobileIndexJSON;
import com.mj.mafeed.util.DBHelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * 手机端首页Dao
 * @author zhaominglei
 * @date 2015-12-10
 * 
 */
public class MobileIndexDao extends BaseDao {
	private static final String TABLE_NAME = "feed_mobile_index";
	
	public void save(Context context, MobileIndexJSON mobileIndexJSON) {
		SQLiteDatabase db = DBHelper.getInstance(context).getWritableDatabase();
		ContentValues contentValues = new ContentValues();
		contentValues.put("mobileindexid", mobileIndexJSON.getMobileindexid());
		contentValues.put("orders", mobileIndexJSON.getOrders());
		contentValues.put("title", mobileIndexJSON.getTitle());
		contentValues.put("source", mobileIndexJSON.getSource());
		contentValues.put("type", mobileIndexJSON.getType());
		contentValues.put("url", mobileIndexJSON.getUrl());
		contentValues.put("price", String.valueOf(mobileIndexJSON.getPrice()));
		contentValues.put("promotionprice", String.valueOf(mobileIndexJSON.getPromotionPrice()));
		contentValues.put("productid", mobileIndexJSON.getProductId());
		db.insert(TABLE_NAME, null, contentValues);
	}
	
	public void deleteAll(Context context) {
		deleteAll(context, TABLE_NAME);
	}
	
	public List<MobileIndexJSON> getMobileIndex(Context context, int type) {
		List<MobileIndexJSON> mobileIndexJSONs = new ArrayList<MobileIndexJSON>();
		SQLiteDatabase  db = DBHelper.getInstance(context).getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from "+TABLE_NAME+" where type=? order by orders asc", new String[]{ String.valueOf(type) });
		while(cursor.moveToNext()) {
			MobileIndexJSON mobileIndexJSON = new MobileIndexJSON();
			mobileIndexJSON.setMobileindexid(cursor.getLong(cursor.getColumnIndex("mobileindexid")));
			mobileIndexJSON.setOrders(cursor.getInt(cursor.getColumnIndex("orders")));
			mobileIndexJSON.setTitle(cursor.getString(cursor.getColumnIndex("title")));
			mobileIndexJSON.setSource(cursor.getString(cursor.getColumnIndex("source")));
			mobileIndexJSON.setType(cursor.getInt(cursor.getColumnIndex("type")));
			mobileIndexJSON.setUrl(cursor.getString(cursor.getColumnIndex("url")));
			mobileIndexJSON.setPrice(new BigDecimal(cursor.getDouble(cursor.getColumnIndex("price"))));
			mobileIndexJSON.setPromotionPrice(new BigDecimal(cursor.getDouble(cursor.getColumnIndex("promotionprice"))));
			mobileIndexJSON.setProductId(cursor.getLong(cursor.getColumnIndex("productid")));
			mobileIndexJSONs.add(mobileIndexJSON);
		}
		cursor.close();
		return mobileIndexJSONs;
	}
}
